<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Api\BaseController;
use App\Http\Services\Oss;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class FileUploadController extends BaseController
{
    public function upload(Request $request)
    {
        $oss = new Oss();
        $is_md5 = $request->get('md5') ?? 1;
        $extension = $this->get_ext();
        if(empty($extension)) {
            return $this->toJson(self::ERROR, [], '文件上传异常');
        }
        $upload_config = $this->get_oss_config($_POST['type'] ?? 1, $extension);
        $size = filesize($_FILES['file']['tmp_name']);
        $fp = fopen($_FILES['file']['tmp_name'], 'rb');
        $content = fread($fp, $size);
        fclose($fp);
        $ossRes = $oss->getAs($upload_config['data'][0]['put_url'], $content, $size);
        if (!$ossRes) {
            return $this->toJson(self::ERROR);
        }
        $data['md5']  = '';
        $md5 = md5_file($_FILES['file']['tmp_name']);
        $data['uri'] = $upload_config['data'][0]['uri'];
        if ($is_md5 == 2) {
            $data['md5'] = $md5;
        }
        return $this->toJson(self::SUCCESS, $data);
    }

    /**
     * 获取二进制文件
     * @return bool|string
     */
    private function get_binary()
    {
        $fp = fopen($_FILES['file']['tmp_name'], 'rb');
        $binary = fread($fp, $_FILES['file']['size'] + 1);
        fclose($fp);
        return $binary;
    }

    /**
     * 获取文件类型
     * @return mixed
     */
    private function get_ext()
    {
        $path_info = pathinfo($_FILES['file']['name']);
        return empty($path_info['extension']) ? '' : $path_info['extension'];
    }

    /**
     * 获取阿里云文件上传参数
     * @return mixed
     */
    private function get_oss_config(int $type = 1, string $ext = 'jpg')
    {
        $res = curl_request(config('kkaudio.kkaudio_api') . "/inner/system/put_file_url", ['type' => $type, 'exts' => $ext, 'noase' => 1], $contentType = 'urlencoded', $httpMethod = 'GET');        
        if ($res['code'] == 0) {
            return $res;
        }
        return '';
    }

    /**
     * 文件上传v2版本
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function uploadV2(Request $request)
    {
        $fileObj = $_FILES['file'] ?? [];
        if (!$fileObj) {
            return $this->toJson(self::ERROR, '文件不存在');
        }

        if ($fileObj['error'] != 0) {
            return $this->toJson(self::ERROR, '文件上传错误');
        }

        $oss = new Oss();
        $is_md5 = $request->get('md5') ?? 1;
        $extension = $this->get_ext();
        if(empty($extension)) {
            return $this->toJson(self::ERROR, [], '文件上传异常');
        }
        $upload_config = $this->get_oss_config($_POST['type'] ?? 1, $extension);
        if (!$upload_config) {
            return $this->toJson(self::ERROR, '文件上传配置错误');
        }

        $md5 = md5_file($fileObj['tmp_name']);
        $uri = $upload_config['data'][0]['uri'];
        $formatUri = ltrim($uri, '/');
        list($msec, $sec) = explode(' ', microtime());
        $msectime = (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);
        $localFilePath = storage_path($msectime . '.' . $extension);
        $bool = move_uploaded_file($_FILES['file']['tmp_name'], $localFilePath);
        if (!$bool) {
            return $this->toJson(self::ERROR, '发生错误，文件移动失败');
        }

        $ossRes = $oss->uploadFile($formatUri, $localFilePath);
        if (!$ossRes) {
            return $this->toJson(self::ERROR, '上传文件过程中发生错误');
        }

        $data['md5']  = '';
        $data['uri'] = $uri;
        if ($is_md5 == 2) {
            $data['md5'] = $md5;
        }

        return $this->toJson(self::SUCCESS, $data);
    }
}
